using System;

using Pegasus.Diagnostics;
using Pegasus.Log4Net;
using Pegasus.Threading;
using Pegasus.Workflow.Service;

namespace Pegasus.Workflow.Service.DefaultServices
{
	/// <summary>
	/// This class used by the default message serivces to schedule timers events.
	/// </summary>
	internal class TimerTask : IScheduleTask
	{
		// Local Instance Values
		private ILog m_log = LogManager.GetLogger( typeof( TimerTask ) );
		private IDispatchTimerTask m_messageService;
		private DateTime m_time;
		private WorkflowEventParameters m_parameters;

		/// <summary>
		/// Initializes a new instance of the <see cref="T:TimerTask"/> class.
		/// </summary>
		/// <param name="messageService">The message service.</param>
		/// <param name="time">The time.</param>
		/// <param name="parameters">The parameters.</param>
		public TimerTask( IDispatchTimerTask messageService, DateTime time, WorkflowEventParameters parameters )
		{
			// Check Parameters
			ParamCode.AssertNotNull( messageService, "messageService" );
			// time is any valid date time
			ParamCode.AssertNotNull( parameters, "parameters" );

			m_messageService = messageService;
			m_time = time;
			m_parameters = parameters;
		}

		/// <summary>
		/// Gets the name of the task.
		/// </summary>
		/// <value>The name of the task.</value>
		public string Name
		{
			get
			{
				return "Workflow Timer Task";
			}
		}

		/// <summary>
		/// Gets a value indicating whether this is a reoccurring task or not.
		/// </summary>
		/// <value>
		/// If <c>true</c> the task will be reschedule after is runs.  If <c>false</c> then the
		/// task will only be executed once.
		/// </value>
		public bool ReoccurringTask
		{
			get
			{
				return false;
			}
		}

		/// <summary>
		/// Gets the next date and time of the next occurrence of the task.
		/// </summary>
		/// <returns>The next occurrence of the task.</returns>
		public DateTime GetNextReoccurrence()
		{
			return m_time;
		}

		/// <summary>
		/// Called to execute the task.
		/// </summary>
		public void RunTask()
		{
			try
			{
				m_messageService.DispatchTimerTask( this, m_parameters );
			}
			catch( Exception e )
			{
				m_log.Error( "Unhandled exception in RunTask() method of MessageServiceTimerTask", e );
				throw;
			}
		}
	}
}
